package com.yhhvip.admin.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.ItemDetailGetRequest;
import com.taobao.api.response.ItemDetailGetResponse;
import com.yhhvip.admin.entity.*;
import com.yhhvip.admin.service.AdminService;
import com.yhhvip.utils.DateUtil;
import com.yhhvip.utils.JsonResult;
import com.yhhvip.utils.StringUtils;
import com.yhhvip.utils.TaoBaoUtil.Item_detail_get_response;
import com.yhhvip.utils.TaoBaoUtil.TaoBaoBean;
import com.yhhvip.utils.TaoBaoUtil.TaoBaoConfig;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class AdminController {

    @Resource
    private AdminService adminService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final Logger log=Logger.getLogger(AdminController.class);
    /*
    * 管理员登录
    * */
    @RequestMapping("admin/loginIn")
    @ResponseBody
    public JsonResult Login(@RequestParam("name") String name, @RequestParam("password") String password) {
        Company company=null;
        if (!StringUtils.isEmpty(name)  && !StringUtils.isEmpty(password)) {
            company = adminService.getLoginDetail(name , password);
            if (null!=company) {
                return JsonResult.ok(company);
            } else {
                return JsonResult.build(412, "用户不存在或密码错误");
            }
            }else if(StringUtils.isEmpty(name)||StringUtils.isEmpty(password)){
                return JsonResult.build(400,"账号或密码不能为空");
        }
        return JsonResult.ok(company);
    }
    /*
     * 分公司登录
     * */
    @RequestMapping("admin/fenLoginIn")
    @ResponseBody
    public JsonResult fenLogin(@RequestParam("name") String name, @RequestParam("password") String password,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        Company company=null;
        if (!StringUtils.isEmpty(name)  && !StringUtils.isEmpty(password)) {
            company = adminService.getfenLoginDetail(name ,password);
            if (null!=company) {
                return JsonResult.ok(company);
            } else {
                return JsonResult.build(412, "用户不存在或密码错误");
            }
        }else if(StringUtils.isEmpty(name)||StringUtils.isEmpty(password)){
            return JsonResult.build(400,"账号或密码不能为空");
        }
        return JsonResult.ok(company);
    }

    @RequestMapping(value = "admin/addOperator", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addOperator(@RequestParam("companyId") String companyId) {
        Boolean flg=false;
        String secretKey=UUID.randomUUID().toString().replaceAll("-", "");
        flg=adminService.isExistSecretKey(secretKey);
        if (!flg){
            return  JsonResult.build(411,"添加失败,秘钥已存在");
        }
        flg=adminService.addOperator(Integer.parseInt(companyId),secretKey);
        if (!flg){
            return  JsonResult.build(507,"添加失败,您添加至尊会员的名额已用完");
        }
        return JsonResult.ok(secretKey);
    }
    @RequestMapping(value = "admin/findOperate", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult findOperate(@RequestParam("companyId") String companyId,@RequestParam("userRole")String userRole,@RequestParam(name = "page",defaultValue = "1")String page,@RequestParam(name="size",defaultValue = "10") String size) {
        return JsonResult.ok(adminService.findOperate(Integer.parseInt(companyId),Integer.parseInt(userRole),(Integer.parseInt(page)-1)*Integer.parseInt(size),Integer.parseInt(size)));
    }
    @RequestMapping(value = "admin/findCompanyallCount", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult findCompanyallCount(@RequestParam("companyId") String companyId) {
        return JsonResult.ok(adminService.findCompanyallCount(Integer.parseInt(companyId)));
    }

    @RequestMapping(value = "admin/addCommodity", method = RequestMethod.POST/*,consumes = "application/json"*/)
    @ResponseBody
    @Transactional
    public JsonResult addCommodity(@RequestParam("cPictureJson") String cPictureJson,/*@RequestBody */Commodity commodity,@RequestParam("manySpecificationOptionsJson") String manySpecificationOptionsJson,@RequestParam("CSRJson") String CSRJson,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
       /* Commodity commodity=new Commodity();*/
        List<CPicture> cPicturelists=new ArrayList<>();
        List<SpecificationOptions> manySpecificationOptionss=new ArrayList<>();
        List<CSRelation> CSRlists=new ArrayList<>();
        CPicture cPicture;
        SpecificationOptions specificationOptions;
        CSRelation csRelation;
        if (null==commodity.getBrandId()){
            throw new RuntimeException("商品信息不能为空!");
        }
            try {
                JSONArray json;
                JSONObject jsonOne;
                //商品图片
                json=JSONArray.parseArray(cPictureJson);
                Calendar calendar=Calendar.getInstance();
                SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//yyyy-MM-dd HH:mm:ss
                for(int i=0;i<json.size();i++){
                    cPicture=new CPicture();
                    jsonOne = json.getJSONObject(i);
                    cPicture.setPictureUrl(jsonOne.get("pictureUrl").toString());
                    cPicture.setIsMainPicture(new Byte(jsonOne.get("isMainPicture").toString()));
                    cPicture.setCreateTime(calendar.getTime());
                    cPicturelists.add(cPicture);
                }
                //商品规格值
                json=JSONArray.parseArray(manySpecificationOptionsJson);
                for(int i=0;i<json.size();i++){
                    specificationOptions=new SpecificationOptions();
                    jsonOne = json.getJSONObject(i);
                    specificationOptions.setSpecificationOptionsValue(jsonOne.get("specificationOptionsValue").toString());
                    specificationOptions.setSpecificationId(Integer.parseInt(jsonOne.get("specificationId").toString()));
                    manySpecificationOptionss.add(specificationOptions);
                }
                commodity.setAmount(0);
                //商品规格关系
                json=JSONArray.parseArray(CSRJson);
                for(int i=0;i<json.size();i++){
                    csRelation=new CSRelation();
                    jsonOne = json.getJSONObject(i);
                    commodity.setAmount(commodity.getAmount()+Integer.parseInt(jsonOne.get("stock").toString()));
                    csRelation.setSpecificationOptionsValue(jsonOne.get("specificationOptionsValue").toString());
                    csRelation.setCostPrice(new BigDecimal(jsonOne.get("costPrice").toString()));
                    csRelation.setStock(Integer.parseInt(jsonOne.get("stock").toString()));
                    csRelation.setZongProportion(new BigDecimal(jsonOne.get("zongProportion").toString()));
                    csRelation.setOtherProportion(new BigDecimal(jsonOne.get("otherProportion").toString()));
                    csRelation.setBale(jsonOne.get("cbale").toString());
                    csRelation.setPrice(csRelation.getCostPrice().add(csRelation.getCostPrice().multiply(csRelation.getZongProportion().add(csRelation.getOtherProportion()))));
                    CSRlists.add(csRelation);
                }
                commodity.setIsDel(new Byte("0"));
                commodity.setSalesAmount(0);
                commodity.setThriftPrice(commodity.getOriginaPrice().subtract(commodity.getSalePrice()));
                adminService.addCommodity(commodity,manySpecificationOptionss,CSRlists,cPicturelists);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("数据错误");
            }
        return JsonResult.ok();
    }
    @RequestMapping(value = "admin/updCommodity", method = RequestMethod.POST/*,consumes = "application/json"*/)
    @ResponseBody
    @Transactional
    public JsonResult updCommodity(@RequestParam("cPictureJson") String cPictureJson,/*@RequestBody */Commodity commodity,@RequestParam("manySpecificationOptionsJson") String manySpecificationOptionsJson,@RequestParam("CSRJson") String CSRJson,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        /* Commodity commodity=new Commodity();*/
        List<CPicture> cPicturelists=new ArrayList<>();
        List<SpecificationOptions> manySpecificationOptionss=new ArrayList<>();
        List<CSRelation> CSRlists=new ArrayList<>();
        CPicture cPicture;
        SpecificationOptions specificationOptions;
        CSRelation csRelation;
        try {
            JSONArray json;
            JSONObject jsonOne;
            //商品图片
            json=JSONArray.parseArray(cPictureJson);
            Calendar calendar=Calendar.getInstance();
            SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//yyyy-MM-dd HH:mm:ss
            for(int i=0;i<json.size();i++){
                cPicture=new CPicture();
                jsonOne = json.getJSONObject(i);
                if (!StringUtils.isEmpty(jsonOne.get("cPictureId").toString())){
                    cPicture.setcPictureId(Integer.parseInt(jsonOne.get("cPictureId").toString()));
                }
                cPicture.setPictureUrl(jsonOne.get("pictureUrl").toString());
                cPicture.setIsMainPicture(new Byte(jsonOne.get("isMainPicture").toString()));
                cPicture.setCreateTime(calendar.getTime());
                cPicturelists.add(cPicture);
            }
            //商品规格值
            json=JSONArray.parseArray(manySpecificationOptionsJson);
            for(int i=0;i<json.size();i++){
                specificationOptions=new SpecificationOptions();
                jsonOne = json.getJSONObject(i);
                if (!StringUtils.isEmpty(jsonOne.get("specificationOptionsId").toString())){
                    specificationOptions.setSpecificationOptionsId(Integer.parseInt(jsonOne.get("specificationOptionsId").toString()));
                }
                specificationOptions.setSpecificationOptionsValue(jsonOne.get("specificationOptionsValue").toString());
                specificationOptions.setSpecificationId(Integer.parseInt(jsonOne.get("specificationId").toString()));
                manySpecificationOptionss.add(specificationOptions);
            }
            commodity.setAmount(0);
            //商品规格关系
            json=JSONArray.parseArray(CSRJson);
            for(int i=0;i<json.size();i++){
                csRelation=new CSRelation();
                jsonOne = json.getJSONObject(i);
                commodity.setAmount(commodity.getAmount()+Integer.parseInt(jsonOne.get("stock").toString()));
                if (!StringUtils.isEmpty(jsonOne.get("cSId").toString())){
                    csRelation.setcSId(Integer.parseInt(jsonOne.get("cSId").toString()));
                }
                csRelation.setSpecificationOptionsValue(jsonOne.get("specificationOptionsValue").toString());
                csRelation.setCostPrice(new BigDecimal(jsonOne.get("costPrice").toString()));
                csRelation.setStock(Integer.parseInt(jsonOne.get("stock").toString()));
                csRelation.setZongProportion(new BigDecimal(jsonOne.get("zongProportion").toString()));
                csRelation.setOtherProportion(new BigDecimal(jsonOne.get("otherProportion").toString()));
                csRelation.setBale(jsonOne.get("cbale").toString());
                csRelation.setPrice(csRelation.getCostPrice().add(csRelation.getCostPrice().multiply(csRelation.getZongProportion().add(csRelation.getOtherProportion()))));
                CSRlists.add(csRelation);
            }
            commodity.setIsDel(new Byte("0"));
            commodity.setSalesAmount(0);
            commodity.setThriftPrice(commodity.getOriginaPrice().subtract(commodity.getSalePrice()));
            adminService.updCommodity(commodity,manySpecificationOptionss,CSRlists,cPicturelists);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据错误");
        }
        return JsonResult.ok();
    }
    @RequestMapping(value = "admin/parentCategoryFindAll",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult parentCategoryFindAll(HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin","*");
        return JsonResult.ok(adminService.parentCategoryFindAll());
    }
    @RequestMapping(value = "admin/topicsActivityMapperAll",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult topicsActivityMapperAll(@RequestParam("isShow") String isShow,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        return JsonResult.ok(adminService.findAlltopicsActivity(isShow));
    }
    @RequestMapping(value = "admin/updimg", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult updimg(@RequestParam("uploadImg") MultipartFile file,HttpServletResponse response,HttpServletRequest request){
        response.setHeader("Access-Control-Allow-Origin", "*");
        String imgName;
        imgName= adminService.updimg(file,request);
        //http://yhhvip.oss-cn-shenzhen.aliyuncs.com/
        return JsonResult.ok(imgName);
    }
    @RequestMapping(value = "admin/delimg", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delimg(@RequestParam("cPictureId") Integer cPictureId,HttpServletResponse response,HttpServletRequest request){
        response.setHeader("Access-Control-Allow-Origin", "*");
        //http://yhhvip.oss-cn-shenzhen.aliyuncs.com/
        return JsonResult.ok(adminService.delimg(cPictureId));
    }
    @RequestMapping(value = "admin/delCommodity", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delCommodity(@RequestParam("commodityId") Integer commodityId){
    return JsonResult.ok(adminService.updCommdityIsdel(commodityId));
    }
    @RequestMapping(value = "admin/commodityAll", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult commodityAll(@RequestParam("brandId") String brandId,@RequestParam("name") String name,@RequestParam(value = "page",defaultValue ="1" ) Integer page,@RequestParam(value = "size",defaultValue = "20") Integer size, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        return JsonResult.ok(adminService.commodityByOtherAll(brandId,name,(page-1)*size,size),adminService.commodityByOtherAllCount(brandId,name,(page-1)*size,size));

    }
    @RequestMapping(value = "admin/commodityById", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult commodityById(@RequestParam("commodityId") Integer commodityId,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        return JsonResult.ok(adminService.commodityById(commodityId));

    }

    @RequestMapping(value = "admin/findSpecificationsBygoods", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult findSpecificationsBygoods(@RequestParam("goodsId") Integer goodsId,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        return JsonResult.ok(adminService.findSpecificationsBygoods(goodsId));
    }
    @RequestMapping(value = "admin/findAllGoods", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult findAllGoods(HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        return JsonResult.ok(adminService.findAllGoods());
    }
    @RequestMapping(value = "admin/brandAll",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult brandAll(HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        return JsonResult.ok(adminService.findAllBrand());
    }
    @RequestMapping(value = "admin/ordersAll", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult ordersById(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime, @RequestParam(name = "userRole") Integer userRole, @RequestParam(name = "brandId") Integer brandId, @RequestParam(name = "ordersId") String ordersId, @RequestParam("ordersStatu") String ordersStatu, @RequestParam(name = "page",defaultValue = "1") Integer page, @RequestParam(name = "size",defaultValue = "10") Integer size, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        Date startTimes=null;
        Date endTimes=null;
        try {
            if(DateUtil.isFormatDate(startTime)){
                startTimes=DateUtil.stringToDate(startTime,"yyyy-MM-dd HH:mm:ss");
            }if(DateUtil.isFormatDate(endTime)){
                DateUtil.stringToDate(endTime,"yyyy-MM-dd HH:mm:ss");
            }
        }catch (Exception e){
            throw new RuntimeException("转换失败!");
        }
        return JsonResult.ok(adminService.ordersAll(startTimes,endTimes,userRole,brandId,ordersId,ordersStatu,page,size),adminService.ordersAllCount(startTimes,endTimes,userRole,brandId,ordersId,ordersStatu,page,size));
    }
    @RequestMapping(value = "admin/ordersById", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult ordersById(@RequestParam(name = "ordersId") String ordersId,HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", "*");
        return JsonResult.ok(adminService.ordersById(ordersId));
    }
    @RequestMapping(value = "admin/addLikeAddCommodity")
    @ResponseBody
    public JsonResult addLikeAddCommodity(){
        TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", TaoBaoConfig.AppKey, TaoBaoConfig.Secret);
        ItemDetailGetRequest req = new ItemDetailGetRequest();
        req.setItemId("564750396273");
        req.setFields("item,price,delivery,skuBase,skuCore,trade,feature,props,debug");
        try {
            ItemDetailGetResponse rsp =  client.execute(req);
            log.info(rsp.getBody());
        }catch (ApiException e){
            log.info(e.getErrMsg());
            throw new RuntimeException("获取淘宝商品信息数据失败!");
        }
        JSONArray json;
        JSONObject jsonOne;
        try{
            json=JSONArray.parseArray("");
            for (int i=0;i<json.size();i++){

            }
        }catch (JSONException e){
            e.printStackTrace();
            throw new RuntimeException("解析失败！");
        }

        return JsonResult.ok();
    }
    @RequestMapping(value = "admin/addTaoBaoCommodity/{taobaoCommodityId}",method = RequestMethod.GET)
    @ResponseBody
    public JsonResult addTaoBaoCommodity(@PathVariable Integer taobaoCommodityId) throws ApiException {

        return JsonResult.ok(adminService.addTaoBaoCommodity(taobaoCommodityId + ""));
    }
}
